package com.epam.task.web.service.command;

import com.epam.task.web.db.DataBaseWriter;
import com.epam.task.web.entity.OrderProduct;
import com.epam.task.web.entity.Status;
import com.epam.task.web.entity.User;
import com.epam.task.web.service.AbstractAction;
import com.epam.task.web.util.logging.LoggerUtil;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddOrder extends AbstractAction {

    private final LoggerUtil logger = new LoggerUtil(Logger.getLogger(AddOrder.class.getClass()));

    @Override
    public String perform(HttpServletRequest request, HttpServletResponse response) {
        DataBaseWriter dataBaseWriter = new DataBaseWriter();

        if (request.getParameter("insert").equals("false")) {
            return "/addOrder.jsp";
        } else {
            try {
                Date dateAdded = (new SimpleDateFormat("yyyy-MM-dd")).parse(request.getParameter("date_added"));
                Status status = createStatusById((Long) findField(find("oc_order_status", "name", request.getParameter("name")), "order_status_id"));
                User customer = createUserById(Long.valueOf(request.getParameter("user_id")));
                User manager = createUserById(Long.valueOf(request.getParameter("manager_id")));
                String comment = request.getParameter("comment");
                OrderProduct orderProduct = createOrderProductById(Long.valueOf(request.getParameter("order_id")));

                dataBaseWriter.insert("oc_order", dateAdded, status.getStatusId(), customer.getId(), manager.getId(), comment, orderProduct.getId());
            } catch (SQLException | ParseException | ClassNotFoundException exception) {
                logger.getExceptionTextFileLogger().error(exception);
            }

            return "/addOrder.jsp";
        }
    }

}
